package com.mojo.concurrent.concurrent_01_thread;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁实现缓存
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2023, 广州九尾信息科技有限公司
 * @date 2023/2/2 17:32
 */
public class ReadAndWriteCache {
    static Map<String, Object> map = new HashMap<>(16);
    static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public static void put(String key, Object val) {
        ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
        writeLock.lock();
        try {
            map.put(key, val);
            System.out.printf("put成功,%s,%s", key, val);
            System.out.println();
        } finally {
            writeLock.unlock();
        }
    }

    public static void get(String key) {
        ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
        readLock.lock();
        Object o;
        try {
            o = map.get(key);
        } finally {
            readLock.unlock();
        }
        System.out.println(o);
    }

    static class CacheThread extends Thread {
        @Override
        public void run() {

        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {

            int finalI = i;
            new Thread(() -> {
                try {
                    TimeUnit.MILLISECONDS.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                put("key", finalI);
            }).start();
        }
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                get("key");
            }
        }).start();
    }
}
